<template>
  <div>
    <div><h1>商品管理</h1></div>
    <!-- 按钮 -->
    <div>
      <el-button plain @click="openAdd"> 商品添加 </el-button>
      <el-button
        type="danger"
        @click="deleteBatch"
        :disabled="multipleSelection.length == 0"
      >
        批量删除
      </el-button>
    </div>
    <div>
      <el-form :inline="true" :model="pageInfoVo" class="demo-form-inline">
        <el-form-item label="id/SPU/商品名称">
          <el-input
            v-model="pageInfoVo.keyWord"
            placeholder="请输入"
            clearable
          />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="loadProdList">查询</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div>
      <el-table
        :data="tableData"
        stripe
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="prodId" label="商品ID" width="100" />
        <el-table-column prop="prodSpu" label="商品SPU" width="100" />
        <el-table-column prop="prodName" label="商品名称" width="150" />
        <el-table-column prop="prodImage" label="商品图片" width="100">
          <template #default="scope">
            <img :src="scope.row.prodImage" style="width: 50px; height: 50px" />
          </template>
        </el-table-column>
        <el-table-column prop="kindName" label="类型名称" width="100" />
        <el-table-column prop="unitName" label="单位" width="100" />
        <el-table-column prop="tagName" label="标签" width="100" />
        <el-table-column prop="brandName" label="品牌名称" width="100" />
        <el-table-column prop="typeName" label="分类名称" width="100" />
        <el-table-column prop="createBy" label="创建人" width="100" />
        <el-table-column prop="createTime" label="创建时间" width="200" />
        <el-table-column label="操作">
          <template #default="scope">
            <el-button
              type="warning"
              size="small"
              @click="handleAtta(scope.row)"
            >
              商品附件
            </el-button>
            <el-button
              size="small"
              type="success"
              @click="handleProdInfo(scope.row)"
            >
              商品明细
            </el-button>
            <el-button
              size="small"
              type="primary"
              @click="handleCheck(scope.row)"
            >
              审核
            </el-button>
            <el-button
              type="danger"
              size="small"
              @click="handleDetele(scope.row)"
            >
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div style="margin-top: 10px">
      <el-pagination
        v-model:current-page="pageInfoVo.pageNum"
        v-model:page-size="pageInfoVo.pageSize"
        :page-sizes="[2, 4, 6, 8]"
        :background="true"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
      />
    </div>
    <!-- 添加对话框 -->
    <div>
      <el-dialog v-model="dialogFormVisible" title="商品添加" width="800">
        <el-form :model="form" ref="ruleFormRef" :rules="rules">
          <el-form-item
            label="商品类型"
            :label-width="formLabelWidth"
            prop="prodKind"
          >
            <el-radio-group v-model="form.prodKind">
              <el-radio
                v-for="item in kindList"
                :value="item.dictValue"
                :key="item.dictId"
                >{{ item.dictName }}</el-radio
              >
            </el-radio-group>
          </el-form-item>
          <el-form-item
            label="商品分类"
            :label-width="formLabelWidth"
            prop="prodType"
          >
            <el-tree-select
              v-model="form.prodType"
              :data="typeList"
              check-strictly
              :render-after-expand="false"
              style="width: 240px"
            />
          </el-form-item>
          <el-form-item
            label="商品名称"
            :label-width="formLabelWidth"
            prop="prodName"
          >
            <el-input v-model="form.prodName" autocomplete="off" />
          </el-form-item>
          <el-form-item label="商品SPU" :label-width="formLabelWidth">
            <el-input v-model="form.prodSpu" autocomplete="off" />
          </el-form-item>
          <el-form-item
            label="商品品牌"
            :label-width="formLabelWidth"
            prop="brandId"
          >
            <el-select v-model="form.brandId" placeholder="请选择商品品牌">
              <el-option
                v-for="item in brandList"
                :label="item.brandName"
                :value="item.brandId"
                :key="item.brandId"
              />
            </el-select>
          </el-form-item>
          <el-form-item
            label="商品单位"
            :label-width="formLabelWidth"
            prop="unitId"
          >
            <el-select v-model="form.unitId" placeholder="请选择商品单位">
              <el-option
                v-for="item in unitList"
                :label="item.dictName"
                :value="item.dictValue"
                :key="item.dictId"
              />
            </el-select>
          </el-form-item>
          <el-form-item
            label="商品标签"
            :label-width="formLabelWidth"
            prop="tagId"
          >
            <el-select v-model="form.tagId" placeholder="请选择商品标签">
              <el-option
                v-for="item in tagList"
                :label="item.dictName"
                :value="item.dictValue"
                :key="item.dictId"
              />
            </el-select>
          </el-form-item>
          <el-form-item
            label="订单类型"
            :label-width="formLabelWidth"
            prop="apprId"
          >
            <el-select v-model="form.apprId" placeholder="请选择订单类型">
              <el-option
                v-for="item in apprList"
                :label="item.dictName"
                :value="item.dictValue"
                :key="item.dictId"
              />
            </el-select>
          </el-form-item>
          <el-form-item
            label="商品缩略图"
            :label-width="formLabelWidth"
            prop="imageUrl"
          >
            <el-upload
              class="avatar-uploader"
              action="http://127.0.0.1:10010/prod/index/uploadFile"
              :headers="headers"
              :show-file-list="false"
              :on-success="handleAvatarSuccess"
            >
              <img v-if="imageUrl" :src="imageUrl" class="avatar" />
              <el-icon v-else class="avatar-uploader-icon"><Plus /></el-icon>
            </el-upload>
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="dialogFormVisible = false">放弃</el-button>
            <el-button type="primary" @click="submitForm(ruleFormRef)">
              提交
            </el-button>
          </div>
        </template>
      </el-dialog>
    </div>
    <!-- 商品附件 -->
    <div>
      <el-dialog v-model="AttaFormVisible" title="添加商品附件" width="800">
        <el-form :model="formAtta">
          <el-form-item label="商品轮播图" :label-width="formLabelWidth">
            <el-upload
              v-model:file-list="fileList"
              action="http://127.0.0.1:10010/prod/type/uploadFile"
              :headers="headers"
              list-type="picture-card"
              :on-preview="handlePictureCardPreview"
              :on-remove="handleRemove"
            >
              <el-icon><Plus /></el-icon>
            </el-upload>
          </el-form-item>
          <el-form-item label="商品视频" :label-width="formLabelWidth">
            <el-upload
              v-model:file-list="videoList"
              class="upload-demo"
              action="http://127.0.0.1:10010/prod/type/uploadFile"
              :headers="headers"
              multiple
              :on-preview="handlePreview"
              :on-remove="handleVideoRemove"
              :before-remove="beforeRemove"
              :limit="1"
              :on-exceed="handleExceed"
            >
              <el-button type="primary">上传视频</el-button>
              <template #tip>
                <div class="el-upload__tip">
                  作用于商品详情页顶部轮插的视频介绍，最大限制20MB，
                </div>
              </template>
            </el-upload>
          </el-form-item>
          <el-form-item label="上架时间" :label-width="formLabelWidth">
            <el-radio-group v-model="formAtta.upFlag">
              <el-radio :value="0">立即上架</el-radio>
              <el-radio :value="1">定时上架</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item
            label=""
            :label-width="formLabelWidth"
            v-if="formAtta.upFlag == 1"
          >
            <el-date-picker
              v-model="formAtta.upTime"
              type="datetime"
              value-format="YYYY-MM-DD HH:mm:ss"
              placeholder="请选择定时上架时间"
            />
          </el-form-item>
          <el-form-item label="定时下架" :label-width="formLabelWidth">
            <el-switch
              v-model="formAtta.downFlag"
              :active-value="1"
              :inactive-value="0"
              inactive-text="立即下架"
              active-text="定时下架"
            />
          </el-form-item>
          <el-form-item
            label=""
            :label-width="formLabelWidth"
            v-if="formAtta.downFlag == 1"
          >
            <el-date-picker
              v-model="formAtta.downTime"
              type="datetime"
              value-format="YYYY-MM-DD HH:mm:ss"
              placeholder="请选择定时下架时间"
            />
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button @click="dialogFormVisible = false">放弃</el-button>
            <el-button type="primary" @click="onsubmitAddAtta">
              提交
            </el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<script setup lang="ts">
import { onMounted, ref } from "vue";
import {
  getPageListProd,
  getDictList,
  getSelectTypeTreeList,
  getBrandAll,
  addProd,
  addProdAtta,
  deleteBatchProd,
  deleteProd,
} from "../api/api";
import { Plus } from "@element-plus/icons-vue";
import { ElMessage, ElMessageBox } from "element-plus";
import type { FormInstance, FormRules } from "element-plus";
import type { UploadProps, UploadUserFile } from "element-plus";
import { useRouter } from "vue-router";

const router = useRouter();

//列表数据
const tableData = ref([]);
//分页条数
const total = ref(0);
//查询条件
const pageInfoVo = ref({
  pageNum: 1,
  pageSize: 4,
  keyWord: "",
});
const handleSizeChange = (val: number) => {
  console.log(`${val} items per page`);
  pageInfoVo.value.pageSize = val;
  loadProdList();
};
const handleCurrentChange = (val: number) => {
  console.log(`current page: ${val}`);
  pageInfoVo.value.pageNum = val;
  loadProdList();
};
// 分页列表
const loadProdList = () => {
  getPageListProd(pageInfoVo.value).then((res) => {
    tableData.value = res.data.data.records;
    total.value = res.data.data.total;
  });
};
const dialogFormVisible = ref(false);
const AttaFormVisible = ref(false);
const formLabelWidth = "140px";
const kindList = ref([]);
const typeList = ref([]);
const brandList = ref([]);
const unitList = ref([]);
const tagList = ref([]);
const apprList = ref([]);
const form = ref({
  prodKind: null,
  prodType: null,
  apprId: null,
  brandId: null,
  createdBy: "",
  createdTime: "",
  prodImage: "",
  prodName: "",
  prodSpu: "",
  prodStatus: null,
  tagId: null,
  unitId: null,
});
const formAtta = ref({
  attaImages: "",
  attaVideo: "",
  downFlag: null,
  downTime: "",
  prodId: null,
  upFlag: null,
  upTime: "",
});
const handleProdInfo = (row: any) => {
  console.log(row);
  router.push('/home/prodinfo/' + row.prodId);
};
const handleCheck = (row: any) => {
  console.log(row);
};

// 单删 删除商品
const handleDetele = (row: any) => {
  console.log(row);

  ElMessageBox.confirm("数据删除后无法恢复，您确认咬删除吗?", "警告", {
    confirmButtonText: "确认",
    cancelButtonText: "放弃",
    type: "warning",
  })
    .then(() => {
      //确认删除
      console.log("确认删除");
      deleteProd(row.prodId).then((res) => {
        if (res.data.code == 200) {
          ElMessage.success("删除成功");
          loadProdList();
        } else {
          ElMessage.error(res.data.msg);
        }
      });
    })
    .catch(() => {
      //放弃删除
      console.log("放弃删除");
    });
};

const multipleSelection = ref<any[]>([]);
const handleSelectionChange = (val: any[]) => {
  multipleSelection.value = val;
  console.log("handleSelectionChange", multipleSelection.value);
};
const deleteBatch = () => {
  let ids = [];
  //参数检查
  if (multipleSelection.value.length == 0) {
    ElMessage.error("请选择要删除的商品");
    return;
  }
  multipleSelection.value.forEach((item) => {
    ids.push(item.prodId);
  });
  ElMessageBox.confirm("数据删除后无法恢复，您确认咬删除吗?", "警告", {
    confirmButtonText: "确认",
    cancelButtonText: "放弃",
    type: "warning",
  })
    .then(() => {
      //确认删除
      console.log("确认删除");
      deleteBatchProd(ids).then((res) => {
        if (res.data.code == 200) {
          ElMessage.success("删除成功");
          loadProdList();
        } else {
          ElMessage.error(res.data.msg);
        }
      });
    })
    .catch(() => {
      //放弃删除
      console.log("放弃删除");
    });
};
const onsubmitAddAtta = () => {
  //获取轮播图地址
  let attaImagesList: any = [];
  fileList.value.forEach((item) => {
    console.log("item", item.response.data);
    attaImagesList.push(item.response.data);
  });
  formAtta.value.attaImages = JSON.stringify(attaImagesList);
  //获取视频地址
  if (videoList.value.length <= 0) {
    ElMessage.error("请上传视频");
    return;
  }
  formAtta.value.attaVideo = videoList.value[0].response.data;
  console.log("formAtta.value", formAtta.value);
  addProdAtta(formAtta.value).then((res) => {
    if (res.data.code == 200) {
      ElMessage.success("商品附件添加成功");
      loadProdList();
      AttaFormVisible.value = false;
    } else {
      ElMessage.error(res.data.msg);
    }
  });
};
const fileList = ref<UploadUserFile[]>([]);
const videoList = ref<UploadUserFile[]>([]);
const dialogImageUrl = ref("");
const dialogVisible = ref(false);
const handleRemove: UploadProps["onRemove"] = (uploadFile, uploadFiles) => {
  console.log(uploadFile, uploadFiles);
};
const handlePictureCardPreview: UploadProps["onPreview"] = (uploadFile) => {
  dialogImageUrl.value = uploadFile.url!;
  dialogVisible.value = true;
};
const handleVideoRemove: UploadProps["onRemove"] = (file, uploadFiles) => {
  console.log(file, uploadFiles);
};

const handlePreview: UploadProps["onPreview"] = (uploadFile) => {
  console.log(uploadFile);
};

const handleExceed: UploadProps["onExceed"] = (files, uploadFiles) => {
  ElMessage.warning(
    `The limit is 3, you selected ${files.length} files this time, add up to ${
      files.length + uploadFiles.length
    } totally`
  );
};

const beforeRemove: UploadProps["beforeRemove"] = (uploadFile, uploadFiles) => {
  return ElMessageBox.confirm(
    `Cancel the transfer of ${uploadFile.name} ?`
  ).then(
    () => true,
    () => false
  );
};
const handleAtta = (row: any) => {
  //清空轮播图
  fileList.value = [];
  //清空视频
  videoList.value = [];
  console.log(row);
  formAtta.value = {
    attaImages: "",
    attaVideo: "",
    downFlag: null,
    downTime: "",
    prodId: null,
    upFlag: null,
    upTime: "",
  };
  formAtta.value.prodId = row.prodId;
  AttaFormVisible.value = true;
};
const ruleFormRef = ref<FormInstance>();
const checkImage = (rule: any, value: any, callback: any) => {
  if (imageUrl.value == null || imageUrl.value == "") {
    return callback(new Error("请上传图片"));
  }
  callback();
};
const rules = ref<FormRules>({
  prodName: [{ required: true, message: "请输入商品名称", trigger: "blur" }],
  prodKind: [
    {
      required: true,
      message: "请选择商品类型",
      trigger: "change",
    },
  ],
  prodType: [
    {
      required: true,
      message: "请选择商品分类",
      trigger: "change",
    },
  ],
  brandId: [
    {
      required: true,
      message: "请选择商品品牌",
      trigger: "change",
    },
  ],
  unitId: [
    {
      required: true,
      message: "请选择商品单位",
      trigger: "change",
    },
  ],
  tagId: [
    {
      required: true,
      message: "请选择商品标签",
      trigger: "change",
    },
  ],
  apprId: [
    {
      required: true,
      message: "请选择商品供应商",
      trigger: "change",
    },
  ],
  imageUrl: [
    {
      validator: checkImage,
      trigger: "blur",
    },
  ],
});
const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate((valid, fields) => {
    if (valid) {
      console.log("submit!");
      onsubmitProd();
    } else {
      console.log("error submit!", fields);
    }
  });
};

const imageUrl = ref("");
const headers = ref({
  token: window.sessionStorage.getItem("token") || "",
});
const handleAvatarSuccess: UploadProps["onSuccess"] = (
  response,
  uploadFile
) => {
  // imageUrl.value = URL.createObjectURL(uploadFile.raw!);
  imageUrl.value = response.data;
};
//提交添加
const onsubmitProd = () => {
  form.value.prodImage = imageUrl.value;
  addProd(form.value).then((res) => {
    if (res.data.code == 200) {
      ElMessage.success("添加成功");
      loadProdList();
      dialogFormVisible.value = false;
    } else {
      ElMessage.error(res.data.msg);
    }
  });
};

const openAdd = () => {
  console.log("openAdd");
  form.value = {
    prodKind: null,
    prodType: null,
    apprId: null,
    brandId: null,
    createdBy: "",
    createdTime: "",
    prodImage: "",
    prodName: "",
    prodSpu: "",
    prodStatus: null,
    tagId: null,
    unitId: null,
  };
  imageUrl.value = "";
  dialogFormVisible.value = true;
};
//页面加载钩子函数
onMounted(() => {
  loadProdList();
  //获取商品类型列表
  getDictList(1).then((res) => {
    if (res.data.code == 200) {
      kindList.value = res.data.data;
    }
  });
  //获取商品单位列表
  getDictList(2).then((res) => {
    if (res.data.code == 200) {
      unitList.value = res.data.data;
    }
  });
  //获取商品标签列表
  getDictList(3).then((res) => {
    if (res.data.code == 200) {
      tagList.value = res.data.data;
    }
  });
  //获取供应商列表
  getDictList(4).then((res) => {
    if (res.data.code == 200) {
      apprList.value = res.data.data;
    }
  });
  //获取商品分类列表
  getSelectTypeTreeList().then((res) => {
    if (res.data.code == 200) {
      typeList.value = res.data.data;
    }
  });
  //获取商品品牌列表
  getBrandAll().then((res) => {
    if (res.data.code == 200) {
      brandList.value = res.data.data;
    }
  });
});
</script>
<style scoped>
.avatar-uploader .avatar {
  width: 178px;
  height: 178px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}
</style>
